from django.db import models
from pets.models import Pet
from django.contrib.gis.db import models as gis_models


class PetDevice(models.Model):
    DEVICE_TYPES = [
        ('C', 'Collar'),
        ('T', 'Tag'),
        ('H', 'Harness'),
    ]

    pet = models.OneToOneField(Pet, on_delete=models.CASCADE, related_name='tracking_device')
    device_id = models.CharField(max_length=50, unique=True)
    device_type = models.CharField(max_length=1, choices=DEVICE_TYPES, default='C')
    battery_level = models.PositiveIntegerField(default=100)
    last_connected = models.DateTimeField(auto_now=True)


class LocationLog(gis_models.Model):
    device = models.ForeignKey(PetDevice, on_delete=models.CASCADE, related_name='location_logs')
    timestamp = models.DateTimeField(auto_now_add=True)
    location = gis_models.PointField()
    accuracy = models.FloatField(help_text="Location accuracy in meters")
    battery_level = models.PositiveIntegerField()

    # 空间索引
    objects = gis_models.Manager()

    def save(self, *args, **kwargs):
        # 更新设备的电池状态
        self.device.battery_level = self.battery_level
        self.device.save()
        super().save(*args, **kwargs)


class SafeZone(gis_models.Model):
    pet = models.ForeignKey(Pet, on_delete=models.CASCADE, related_name='safe_zones')
    name = models.CharField(max_length=100)
    area = gis_models.PolygonField()
    is_active = models.BooleanField(default=True)

    objects = gis_models.Manager()